package com.tangding.common.scripts.javascript;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import com.tangding.common.logx.LogHelp;
import com.tangding.common.utils.Utils;

import jdk.nashorn.api.scripting.NashornScriptEngineFactory;

/**
 * @description java调用js代码
 *
 * @author Ranger
 * @version 2017年9月1日_下午1:36:45
 *
 */
@SuppressWarnings("restriction")
public class NashornService {
	private static NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
	private static ScriptEngine scriptEngine = factory.getScriptEngine(new String[]{"--global-per-engine"});
	private static final Map<String, CompiledScript> jse = new ConcurrentHashMap<String, CompiledScript>();
	
	public static CompiledScript get(String formula) {
		String key = Utils.getMD5(formula);
		if (jse.get(key) == null) {
			set(key, formula);
		}
		return jse.get(key);
	}
	
	private static void set(String key, String formula) {
		try {
			jse.put(key, ((Compilable) scriptEngine).compile(formula));
		} catch (ScriptException e) {
			LogHelp.doLogException(e);
		}
	}
	
	/**
	 * 执行js代码
	 * 
	 * @param formula
	 * @param params
	 * @return
	 */
	public static Object executeJsContent(String formula, Bindings bindings) {
		try {
			Object result = get(formula).eval(bindings);
			return result;
		} catch (ScriptException e) {
			LogHelp.doLogException(e);
		}
		return null;
	}
}